package com.duzq.ws;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebService()
public class WebServiceDemo {

    /**
     * Demo 1，简单的 WebService 接口
     * @param name
     * @return
     */
    @WebMethod()
    public String demo1(String name) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String df = sdf.format(new Date());

        String result = df + " Hello, world, from " + name;
        System.out.println(result);
        return result;
    }

    /**
     * Demo 2，项目中实际会发生的调用
     * @param request 入参请求
     * @return res
     */
    @WebMethod(action = "getOrderInfo")
    public WebServiceResponse getOrderInfo(WebServiceRequest request) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String df = sdf.format(new Date());

        System.out.println(df + "getOrderInfo 被调用");
        // 默认返回结果失败
        WebServiceResponse response = new WebServiceResponse();
        response.setCode(500);

        // 参数校验
        if (request == null) {
            response.setMsg("请求信息不能为空");
            return response;
        }
        if (request.getOrderInfo() == null) {
            response.setMsg("查询条件不能为空");
            return response;
        }
        if (request.getOrderInfo().getOrderId() == null) {
            response.setMsg("订单ID不能为空");
            return response;
        }
        // 成功处理场景
        response.setCode(200);
        // 模拟实际业务处理...
        OrderInfo orderInfo = getOrderInfo(request.getOrderInfo().getOrderId());
        response.setOrderInfo(orderInfo);
        return response;
    }

    /**
     * 模拟DB查询
     * @param orderId
     * @return
     */
    private OrderInfo getOrderInfo(Integer orderId) {
        if (orderId != null && !Integer.valueOf(1).equals(orderId)) {
            return null;
        }
        OrderInfo res = new OrderInfo();
        res.setOrderId(1);
        res.setOrderCode("D1001");
        res.setBuyerName("张三");
        res.setProductName("冰可乐");
        res.setSellerName("李四小卖部");
        res.setTotalWeight(new BigDecimal(1));
        res.setTotalMoney(new BigDecimal(6.5));
        res.setCreateDate(new Date());
        return res;
    }

    public static void main(String[] argv) {
        // 发布服务
        Object implementor = new WebServiceDemo();
        String address = "http://localhost:9000/WebServiceDemo";
        Endpoint.publish(address, implementor);
        System.out.println("服务开启...");
    }
}
